﻿using MesBSW.BLL.Mes;
using MesBSW.DAL.MesDB;
using MesBSW.Tools;
using SqlSugar;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;

namespace MesBSW.View.Dialog.Role
{
    /// <summary>
    /// 异常工单判断状态用小窗体
    /// </summary>
    public partial class AbnormalOrderDia : UIEditForm
    {
        private List<SiteInfo> _site_list = new List<SiteInfo>();
        private ExcepOrderControler _ctrl = new ExcepOrderControler();

        private SqlSugarClient Db = SqlSugares.GetInstance();

        public AbnormalOrderDia()
        {
            InitializeComponent();
        }

        public AbnormalOrderDia(string ProdNumber, int curr_site_id, string site_name)
        {
            InitializeComponent();
            this.OrderNo.Text = ProdNumber;
            // 向 ComboBox 控件添加数据项
            this.ComboBoxRole.Items.Add("普通异常");
            this.ComboBoxRole.Items.Add("严重异常");
            SelectSiteAndRepair(curr_site_id, site_name);

        }
        /// <summary>
        /// 确认并修改数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOK_Click_1(object sender, EventArgs e)
        {
            var selectedItem = this.ComboBoxRole.SelectedItem;
            if (selectedItem == null)
            {
                ShowWarningDialog("请选择异常");
                UITextBox edit = new UITextBox();
                edit.Focus();
                return;
            }
            //查询出来工单ID，数量，当前站点
            string sql = $@"select
                                T1.id,			
	                            prod_qty,		
	                            T1.curr_site_id,
	                            T2.site_name	
                            from
                                target_prod_process T1
	                            LEFT JOIN site_info T2 ON T1.curr_site_id = T2.id
                            where
                                prod_number = '{this.OrderNo.Text}'";
            var dysql = Db.SqlQueryable<dynamic>(sql).ToList();
            //查询当前工单异常数量
            var sumResult = Db.SqlQueryable<ProdAbnormal_Detail>($@"
            select
	            sum(abnormal_qty) abnormal_qty
            from
	            Abnormal_Detail
            where
	            end_time is null and prod_number = '{this.OrderNo.Text}'").ToList();
            dynamic dy = sumResult;

            if (this.CBOabnormal_qty.Text.ToDecimal() + dy[0].abnormal_qty > dysql[0].prod_qty)
            {
                UITextBox edit = new UITextBox();
                ShowWarningDialog("异常数量不能超过工单总数！工单总数为" + dysql[0].prod_qty + "未处理的异常数量为" + dy[0].abnormal_qty);
                edit.Focus();
                return;
            }
            if (this.CBOabnormal_qty.Text == "")
            {
                ShowWarningDialog("异常数量不能为0");
                return;
            }
            string[] resultArray = this.uiComboBox1.SelectedItem.ToString().Replace(",", "").Replace("[", "").Replace("]", "").Split();
            var ValueMember = uiComboBox2.ValueMember;
            if (ValueMember == null)
            {
                UITextBox edit = new UITextBox();
                ShowWarningDialog("未选择异常原因");
                edit.Focus();
                return;
            }
            ProdAbnormal_Detail P1 = new ProdAbnormal_Detail();
            P1.prod_id = dysql[0].id;//工单ID
            P1.prod_number = this.OrderNo.Text;//工单号
            P1.site_id = ValueMember.ToInt();//站点ID
            P1.site_name = this.uiComboBox2.Text;//站点名称
            P1.abnormal_qty = this.CBOabnormal_qty.Text.ToDecimal();//异常数量
            P1.status_id = (selectedItem.ToString() == "普通异常") ? 21 : 7;//普通异常21，严重7
            P1.status_name = selectedItem.ToString();//异常名称
            P1.reason_id = resultArray[1].ToInt();//异常ID
            P1.reason_name = resultArray[0];//异常名称
            P1.remark = this.CBORemark.Text;//备注
            P1.create_date = DateTime.Now;//创建时间
            P1.create_user = MainFrm.LoginUser.user_name;//创建人
            P1.begin_time = DateTime.Now;//异常开始时间
            Db.Insertable(P1).ExecuteCommand();
            if (selectedItem.ToString() == "普通异常")
            {
                var list = Db.SqlQueryable<object>($@"select * from target_prod_process where prod_number = '{this.OrderNo.Text}' and err_status = 7").ToList();
                if (list.Count == 0)
                {
                    //修改工单表状态
                    Db.Ado.ExecuteCommand($@"update target_prod_process set err_status = 21 where prod_number = '{this.OrderNo.Text}'");
                    this.Close();
                }
            }
            if (selectedItem.ToString() == "严重异常")
            {
                //修改工单表状态
                Db.Ado.ExecuteCommand($@"update target_prod_process set err_status = 7 where prod_number = '{this.OrderNo.Text}'");
                this.Close();
            }
        }
        /// <summary>
        /// 限制只能输入数字
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void abnormal_qty_KeyPress(object sender, KeyPressEventArgs e)
        {
            // 允许输入:数字、退格键(8)、全选(1)、复制(3)、粘贴(22)
            if (!Char.IsDigit(e.KeyChar) && e.KeyChar != 8 &&
            e.KeyChar != 1 && e.KeyChar != 3 && e.KeyChar != 22)
            {
                e.Handled = true;
            }
        }
        /// <summary>
        /// 查询站点和不良
        /// </summary>
        /// <param name="curr_site_id"></param>
        private void SelectSiteAndRepair(int curr_site_id, string site_name)
        {
            this.uiComboBox2.Items.Clear();
            this.uiComboBox1.Items.Clear();
            //查询站点
            string sql = $@"select
	            id,
                site_name
            from
	             site_info";
            var list = Db.SqlQueryable<object>(sql).ToList();
            dynamic dylist = list;
            for (int i = 0; i < list.Count; i++)
            {
                this.uiComboBox2.Items.Add(new KeyValuePair<string, int>(dylist[i].site_name, dylist[i].id));
            }
            this.uiComboBox2.DisplayMember = "site_name";
            this.uiComboBox2.Text = site_name;
            this.uiComboBox2.ValueMember = curr_site_id.ToString();
            ////查询不良
            //sql = $@"select
	           // id,reason
            //from
	           //  repair_reason
            //where
            //     site_id = '{curr_site_id}'";
            //list = Db.SqlQueryable<object>(sql).ToList();
            //dylist = list;
            //for (int i = 0; i < list.Count; i++)
            //{
            //    this.uiComboBox1.Items.Add(new KeyValuePair<string, int>(dylist[i].reason, dylist[i].id));
            //}
        }
        /// <summary>
        /// 更换站点下拉框事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiComboBox2_SelectedValueChanged_1(object sender, EventArgs e)
        {
            var nmsl = this.uiComboBox2.SelectedValue;
            if (nmsl != null)
            {
                string[] resultArray = nmsl.ToString().Replace(",", "").Replace("[", "").Replace("]", "").Split();
                SelectSiteAndRepair(resultArray[1].ToInt(), resultArray[0]);
            }
        }

        private void AbnormalOrderDia_Load(object sender, EventArgs e)
        {
            List<RepairReason> tmpList = new List<RepairReason>();
            DataTable dt = this.ChangeReasonListToDataTable(null).Clone();
            this._site_list = this._ctrl.FindAllSiteInfo();

            if (this._site_list != null && this._site_list.Count > 0)
            {
                var query = this._site_list.Where(s => s.IsFinal == 1);
                //if (query != null && query.Count() > 0)
                //{
                //    tmpList = this._ctrl.SearchRepairReasonForSite(query.First<SiteInfo>().ID);
                //}
                foreach (var item in query)
                {
                    tmpList.AddRange(this._ctrl.SearchRepairReasonForSite(item.ID).Where(s => s.IsDel == 0));
                }

                var distinctRows = this.ChangeReasonListToDataTable(tmpList).AsEnumerable().GroupBy(row => row["reason"])
          .Select(group => group.First());

                if (distinctRows.Count() > 0)
                {
                    dt = distinctRows.CopyToDataTable();

                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        this.uiComboBox1.Items.Add(new KeyValuePair<string, int>(dt.Rows[i]["reason"].ToString(),Convert.ToInt32(dt.Rows[i]["id"])));
                    } 

                    //uiComboBox1.DataSource = dt;
                    uiComboBox1.DisplayMember = "reason";
                    uiComboBox1.ValueMember = "id";
                    //foreach (DataRow dr in dt.Rows)
                    //{
                    //    uiComboBox1.Items.Add(dr["reason"] + dr["id"]);
                    //}
                }
            }

            //dt = this.ChangeReasonListToDataTable(tmpList);
            //uiComboBox1.DataSource = dt;
            //uiComboBox1.ValueMember = "reason";
            //uiComboBox1.SelectedValue = "reason";
        }

        private DataTable ChangeReasonListToDataTable(List<RepairReason> reasonList)
        {
            DataTable resDt = new DataTable();
            resDt.Columns.Add("id", typeof(int));
            resDt.Columns.Add("site_id", typeof(int));
            resDt.Columns.Add("site_name", typeof(string));
            resDt.Columns.Add("reason", typeof(string));
            resDt.Columns.Add("is_del", typeof(bool));

            if (reasonList != null && reasonList.Count > 0)
            {
                foreach (var item in reasonList)
                {
                    DataRow addRow = resDt.NewRow();
                    addRow["id"] = item.ID;
                    addRow["site_id"] = item.SiteID;
                    addRow["site_name"] = item.SiteName;
                    addRow["reason"] = item.Reason;
                    addRow["is_del"] = item.IsDel == 1 ? true : false;
                    resDt.Rows.Add(addRow);
                }
            }
            return resDt;
        }
    }
}
